package com.amu.aidemo.android

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.core.content.ContextCompat
import com.amu.aidemo.ui.VoiceAssistantScreen
import com.amu.aidemo.ui.TestScreen
import com.amu.aidemo.ui.model.VoiceAssistantUiState
import java.util.logging.Level
import java.util.logging.Logger

class MainActivity : ComponentActivity() {
    
    private lateinit var voiceAssistantManager: VoiceAssistantManager
    private lateinit var moduleTestManager: ModuleTestManager
    
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        if (isGranted) {
            voiceAssistantManager.initialize()
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 关闭 OkHttp 的详细日志
        try {
            Logger.getLogger("okhttp3").level = Level.SEVERE
            Logger.getLogger("okhttp.Http2").level = Level.SEVERE
            Logger.getLogger("okhttp.TaskRunner").level = Level.SEVERE
            Logger.getLogger("okhttp.OkHttpClient").level = Level.SEVERE
        } catch (e: Exception) {
            // 忽略异常
        }
        
        // 从 ApiConfig 读取 API Keys（修改后立即生效，无需 Clean）
        voiceAssistantManager = VoiceAssistantManager(
            context = this,
            // 讯飞语音识别（IAT）
            xfyunIatAppId = com.amu.aidemo.android.config.ApiConfig.XFYUN_IAT_APP_ID,
            xfyunIatApiKey = com.amu.aidemo.android.config.ApiConfig.XFYUN_IAT_API_KEY,
            xfyunIatApiSecret = com.amu.aidemo.android.config.ApiConfig.XFYUN_IAT_API_SECRET,
            // 讯飞语音合成（TTS）
            xfyunTtsAppId = com.amu.aidemo.android.config.ApiConfig.XFYUN_TTS_APP_ID,
            xfyunTtsApiKey = com.amu.aidemo.android.config.ApiConfig.XFYUN_TTS_API_KEY,
            xfyunTtsApiSecret = com.amu.aidemo.android.config.ApiConfig.XFYUN_TTS_API_SECRET,
            // 智谱 AI
            zhipuApiKey = com.amu.aidemo.android.config.ApiConfig.ZHIPU_API_KEY,
            // 唤醒词提示音（从 res/raw 目录加载）
            wakeWordSoundResId = try { com.amu.voiceassistant.android.R.raw.hi_yue } catch (e: Exception) { null }
        )
        
        // 初始化模块测试管理器
        moduleTestManager = ModuleTestManager(
            context = this,
            xfyunIatAppId = com.amu.aidemo.android.config.ApiConfig.XFYUN_IAT_APP_ID,
            xfyunIatApiKey = com.amu.aidemo.android.config.ApiConfig.XFYUN_IAT_API_KEY,
            xfyunIatApiSecret = com.amu.aidemo.android.config.ApiConfig.XFYUN_IAT_API_SECRET,
            xfyunTtsAppId = com.amu.aidemo.android.config.ApiConfig.XFYUN_TTS_APP_ID,
            xfyunTtsApiKey = com.amu.aidemo.android.config.ApiConfig.XFYUN_TTS_API_KEY,
            xfyunTtsApiSecret = com.amu.aidemo.android.config.ApiConfig.XFYUN_TTS_API_SECRET,
            zhipuApiKey = com.amu.aidemo.android.config.ApiConfig.ZHIPU_API_KEY
        )
        
        setContent {
            MyApplicationTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    VoiceAssistantApp(voiceAssistantManager, moduleTestManager)
                }
            }
        }
        
        // 检查并请求录音权限
        checkAndRequestPermission()
    }
    
    private fun checkAndRequestPermission() {
        when {
            ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.RECORD_AUDIO
            ) == PackageManager.PERMISSION_GRANTED -> {
                voiceAssistantManager.initialize()
            }
            else -> {
                requestPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
            }
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        voiceAssistantManager.release()
        moduleTestManager.release()
    }
}

@Composable
fun VoiceAssistantApp(
    manager: VoiceAssistantManager,
    testManager: ModuleTestManager
) {
    var uiState by remember { mutableStateOf(VoiceAssistantUiState()) }
    var showTestScreen by remember { mutableStateOf(false) }
    
    // 监听状态变化
    DisposableEffect(manager) {
        manager.onStateChanged = { newState ->
            uiState = newState
        }
        onDispose {
            manager.onStateChanged = null
        }
    }

    if (showTestScreen) {
        TestScreen(
            onBack = { showTestScreen = false },
            onStartAsr = { onRealtimeResult ->
                testManager.startAsr(onRealtimeResult)
            },
            onStopAsr = { onResult ->
                testManager.stopAsr(
                    onResult = onResult,
                    onError = { error -> onResult("错误: $error") }
                )
            },
            onTestLlm = { question, onResult ->
                testManager.testLlm(
                    question = question,
                    onResult = onResult,
                    onError = { error -> onResult("错误: $error") }
                )
            },
            onTestTts = { text ->
                testManager.testTts(
                    text = text,
                    onError = { error -> 
                        // 可以添加 Toast 提示
                    }
                )
            }
        )
    } else {
        VoiceAssistantScreen(
            uiState = uiState,
            onMicClick = {
                manager.manualTrigger()
            },
            onStopAll = {
                manager.stopAll()
            },
            onTestClick = {
                showTestScreen = true
            },
            modifier = Modifier.fillMaxSize()
        )
    }
}
